package com.ruoyi.personnel.oa.approve.service;

import com.ruoyi.DingDing.Domain.DingDingText;
import com.ruoyi.constant.ERPConstant;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.personnel.oa.approve.domain.ApproveDomain;
import com.ruoyi.personnel.oa.approve.domain.ApproveCond;
import com.ruoyi.personnel.oa.approve.domain.ApproveDto;
import com.ruoyi.personnel.oa.approve.domain.ApproveRecord;
import com.ruoyi.personnel.oa.approve.mapper.ApproveMapper;
import com.ruoyi.produce.material.mapper.ProduceMaterialMapper;
import com.ruoyi.produce.process.planoutsource.mapper.ProducePlanOutsourceMapper;
import com.ruoyi.produce.process.planself.mapper.ProducePlanSelfMapper;
import com.ruoyi.produce.process.receiving.domain.ReceivingReportDomain;
import com.ruoyi.produce.process.receiving.domain.ReceivingReportDto;
import com.ruoyi.produce.process.receiving.mapper.ReceivingReportMapper;
import com.ruoyi.produce.process.receiving.service.IReceivingReportService;
import com.ruoyi.produce.process.worksheet.mapper.ProduceWorkSheetMapper;
import com.ruoyi.psi.purchase.order.domain.PurchaseOrder;
import com.ruoyi.psi.purchase.order.domain.PurchaseOrderList;
import com.ruoyi.psi.purchase.order.mapper.PurchaseOrderMapper;
import com.ruoyi.psi.sale.delivery.mapper.SaleDeliveryMapper;
import com.ruoyi.psi.sale.delivery.service.ISaleDeliveryService;
import com.ruoyi.psi.sale.order.mapper.SaleOrderMapper;
import com.ruoyi.psi.sale.salereturn.mapper.SaleReturnMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * 审批
 * 业务处理层
 */
@Service
public class ApproveServiceImpl implements IApproveService {
    @Autowired
    private ApproveMapper approveMapper;
    @Autowired
    private ReceivingReportMapper receivingReportMapper;//验收单
    @Autowired
    private IReceivingReportService receivingReportService; //验收单接口
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper; //采购订单
    @Autowired
    private ProducePlanSelfMapper producePlanSelfMapper; //生产计划
    @Autowired
    private SaleOrderMapper saleOrderMapper; //销售订单
    @Autowired
    private SaleDeliveryMapper saleDeliveryMapper; //销售出库
    @Autowired
    private ISaleDeliveryService saleDeliveryService; //销售出库
    @Autowired
    private SaleReturnMapper saleReturnMapper; //销售退回
    @Autowired
    private ProduceWorkSheetMapper workSheetMapper; //加工单
    @Autowired
    private ProduceMaterialMapper produceMaterialMapper; //领料单
    @Autowired
    private ProducePlanOutsourceMapper producePlanOutsourceMapper; //委外

    /**
     * 根据搜索条件所有审批记录
     *
     * @param cond 搜索条件
     * @return
     */
    @Override
    public List<ApproveDto> selectApproveList(ApproveCond cond) {
        List<ApproveDto> approveList = approveMapper.selectApproveList(cond);
        for (ApproveDto s : approveList) {
            if (StringUtils.isNotNull(approveMapper.selectAllApproveRecordById(s.getApproveId()))) {
                // 存在
                s.setApproveRecords(approveMapper.selectAllApproveRecordById(s.getApproveId()));
            }
        }
        return approveList;
    }
    /**
     * 更新审批人
     *
     * @param approve 搜索条件
     * @return
     */
    @Override
    public int updateApprover(ApproveDomain approve) throws Exception {
        if (!StringUtils.isNotNull(approveMapper.selectApproveById(approve.getApproveId()))) {
            // 不存在
            return 0;
        }
        if (approve.getApproveStatus().equals(ERPConstant.Approval_Completed)) { //完成状态完成
            // 最高一级审批人，审批完成
            approve.setApproveStatus(ERPConstant.Approval_Success);
            approve.setCurrentApprover(ERPConstant.Approval_Completed_Approver); //当前审核人为空
            String associationId = approve.getAssociationId();
            switch (approve.getApproveType()) {
                case ERPConstant.Approval_Type_Storage: // 入库审批
                    // 将审批标志位置1
                    receivingReportMapper.completeApprovalFlag(associationId);
                    // 如果是入库审批，将验收数量入库。
                    ReceivingReportDomain receivingReportDomain = createReceivingReportDomain(associationId);
                    receivingReportService.receivingReportStorage(receivingReportDomain);

                    // 如果是采购订单入的库，将该条记录的入库状态置为1
                    ReceivingReportDto receivingReport = receivingReportService.selectReceivingReportById(associationId);//拿到验收单
                    if (receivingReport.getSourceType().equals(ERPConstant.RECEIVING_PURCHASE)) { //采购
                        PurchaseOrderList purchaseOrderSub = purchaseOrderMapper.selectPurchaseOrderListById(receivingReport.getWorkSheetId(), receivingReport.getProduceId());//拿到该详情数据记录
                        purchaseOrderSub.setPurchaseOrderStatus(ERPConstant.RECEIVING_WAREHOUSED); //该子表入库
                        purchaseOrderMapper.updatePurchaseOrderList(purchaseOrderSub);
                        List<PurchaseOrderList> purchaseOrderList = purchaseOrderMapper.selectNotStoragePurchaseOrderById(receivingReport.getWorkSheetId()); //查询该采购订单的详情表
//                    System.out.println("详情表==========================" + purchaseOrderList + "规模=================" + purchaseOrderList.size());
                        if (purchaseOrderList.size() == 0) { //判断一下是否所有子表均入库，如果都入库将主表设置为入库
                            PurchaseOrder purchaseOrder = purchaseOrderMapper.selectPurchaseOrderById(receivingReport.getWorkSheetId());
                            purchaseOrder.setStorageStatus(ERPConstant.RECEIVING_WAREHOUSED); //主表入库
                            Timestamp date = new Timestamp(new Date().getTime());
                            purchaseOrder.setActualStorageTime(date); //实际入库时间
                            purchaseOrderMapper.updatePurchaseOrder(purchaseOrder);
                        }
                    }
                    break;
                case ERPConstant.APPROVAL_TYPE_PRODUCE_PLAN: // 生产计划审批
                    // 将审批标志位置1
                    producePlanSelfMapper.completeApprovalFlag(associationId);
                    break;
                case ERPConstant.Approval_Type_Purchase: // 采购审批
                    // 将审批标志位置1
                    purchaseOrderMapper.completeApprovalFlag(associationId);
                    break;
                case ERPConstant.APPROVAL_TYPE_SALE_ORDER: // 销售订单
                    // 将审批标志位置1
                    saleOrderMapper.completeApprovalFlag(associationId);
                    break;
                case ERPConstant.APPROVAL_TYPE_SALE_DELIVERY: // 销售订单出库
                    // 将审批标志位置1
                    saleDeliveryMapper.completeApprovalFlag(associationId);
                    break;
                case ERPConstant.APPROVAL_TYPE_SALE_RETURN: // 销售退回
                    // 将审批标志位置1
                    saleReturnMapper.completeApprovalFlag(associationId);
                    // 库存增加
                    break;
                case ERPConstant.APPROVAL_TYPE_WORKSHEET: // 加工单
                    // 将审批标志位置1
                    workSheetMapper.completeApprovalFlag(associationId);
                    break;
                case ERPConstant.APPROVAL_TYPE_PRODUCE_MATERIAL: // 领料单
                    // 将审批标志位置1
                    produceMaterialMapper.completeApprovalFlag(associationId);
                    break;
                case ERPConstant.APPROVAL_TYPE_PRODUCE_OUT_PLAN: // 委外加工
                    // 将审批标志位置1
                    producePlanOutsourceMapper.completeApprovalFlag(associationId);
                    break;
            }
        }
        // 添加审批记录
        List<ApproveRecord> approveRecords = approve.getApproveRecords();
        for (ApproveRecord s : approveRecords) {
            s.setApproveStatus(ERPConstant.Approval_Success); //通过
            approveMapper.insertApproveRecord(s);
        }
        Long currentApprover = approve.getCurrentApprover();
        DingDingText dingDingText = new DingDingText();
        dingDingText.BatchRobotText(currentApprover);
        return approveMapper.updateApprover(approve);
    }

    /**
     * 审批拒绝
     *
     * @param approve
     * @return
     */
    @Override
    public int refuseApprove(ApproveDomain approve) {
        String associationId = approve.getAssociationId();
        List<ApproveRecord> approveRecords = approve.getApproveRecords();
        switch (approve.getApproveType()) {
            // 将审批标志位置2 (拒绝)
            case ERPConstant.APPROVAL_TYPE_PRODUCE_PLAN: // 生产计划审批
                producePlanSelfMapper.refuseApprovalFlag(associationId);
                break;
            case ERPConstant.Approval_Type_Storage: // 入库审批
                receivingReportMapper.refuseApprovalFlag(associationId);
                //数量回0

                break;
            case ERPConstant.Approval_Type_Purchase: // 采购审批
                purchaseOrderMapper.refuseApprovalFlag(associationId);
                break;
            case ERPConstant.APPROVAL_TYPE_SALE_ORDER: // 销售订单
                saleOrderMapper.refuseApprovalFlag(associationId);
                saleOrderMapper.updateRefuseApprovalRemark(associationId, approveRecords.get(0).getRefuseReason()); //更新拒绝之后的备注
                break;
            case ERPConstant.APPROVAL_TYPE_SALE_DELIVERY: // 销售订单出库
                saleDeliveryMapper.refuseApprovalFlag(associationId);
                break;
            case ERPConstant.APPROVAL_TYPE_SALE_RETURN: // 销售退回
                // 将审批标志位置1
                saleReturnMapper.refuseApprovalFlag(associationId);
                break;
            case ERPConstant.APPROVAL_TYPE_WORKSHEET: // 加工单
                workSheetMapper.refuseApprovalFlag(associationId);
                break;
            case ERPConstant.APPROVAL_TYPE_PRODUCE_MATERIAL: // 领料单
                produceMaterialMapper.refuseApprovalFlag(associationId);
                break;
            case ERPConstant.APPROVAL_TYPE_PRODUCE_OUT_PLAN: // 领料单
                producePlanOutsourceMapper.refuseApprovalFlag(associationId);
                break;
        }
        // 添加审批记录
        for (ApproveRecord s : approveRecords) {
            s.setApproveStatus(ERPConstant.Approval_Not_Success); //不通过
            approveMapper.insertApproveRecord(s);
        }
        return approveMapper.refuseApprove(approve);
    }

    /**
     * 生成一个验收单的domain对象
     *
     * @param receivingReportId
     * @return
     */
    public ReceivingReportDomain createReceivingReportDomain(String receivingReportId) {
        ReceivingReportDto receivingReportDto = receivingReportMapper.selectReceivingReportById(receivingReportId); //根据验收单编号查询验收单信息
        // 生成实体类对象并赋值
        ReceivingReportDomain receivingReportDomain = new ReceivingReportDomain();
        receivingReportDomain.setReceivingReportId(receivingReportDto.getReceivingReportId());
        receivingReportDomain.setWorkSheetId(receivingReportDto.getWorkSheetId());
        receivingReportDomain.setSourceType(receivingReportDto.getSourceType());
        receivingReportDomain.setProduceId(receivingReportDto.getProduceId());
        receivingReportDomain.setReceivingReportNumber(receivingReportDto.getReceivingReportNumber());
        receivingReportDomain.setUnqualifiedNumber(receivingReportDto.getUnqualifiedNumber());
        receivingReportDomain.setStorageFlag("1");
        receivingReportDomain.setWarehousingNumber(receivingReportDto.getReceivingReportNumber() - receivingReportDto.getUnqualifiedNumber()); //验收数量 - 不合格数量 = 入库数量
        receivingReportDomain.setWarehouseId(receivingReportDto.getWarehouseId());
        receivingReportDomain.setStaffInspectId(receivingReportDto.getStaffInspectId());
        receivingReportDomain.setCreateTime(receivingReportDto.getCreateTime());
        receivingReportDomain.setRemark(receivingReportDto.getRemark());
        return receivingReportDomain;
    }
    public int selectApproveByRoleId(ApproveCond cond){
        List<ApproveDto> approveList = approveMapper.selectApproveByRoleId(cond);

        return  approveList.size();

    };

}
